//
//  DatesAndTimesExample.swift
//  SwiftCode
//
//  Created by yuhus on 2023/10/8.
//

import Foundation
import UIKit

class DatesAndTimesExample: ListViewController {
  override func getItemCount() -> Int {
    data.count
  }
  
  override func getItem(_ indexPath: IndexPath) -> Item {
    data[indexPath.row]
  }
  
  private lazy var data: [Item] = [
    .init(title: "Date", description: "初始化", action: dateTest),
    .init(title: "DateComponentsFormatter", description: "About 5 minutes remaining", action: about5minRemaining),
    .init(title: "DateComponentsFormatter", description: "计时器格式", action: timing),
    .init(title: "DateIntervalFormatter", description: "相隔 1 天的日期", action: oneDayApart),
  ]
}

private func dateTest() {
  let birth: Double = 1133948983438 // ms
  debugPrint(Date(timeIntervalSince1970: birth / 1000))
  
  
  debugPrint("UTC", Date())
  
  let accessTokenExpire: Double = 21600000
  debugPrint(Date(timeIntervalSinceNow: accessTokenExpire / 1000))
  
  let date1 = Date(timeIntervalSince1970: birth / 1000)
  debugPrint(date1.timeIntervalSince1970)
}

/// 还剩约5分钟
private func about5minRemaining() {
  let formatter = DateComponentsFormatter()
  formatter.unitsStyle = .full
  formatter.includesApproximationPhrase = true
  formatter.includesTimeRemainingPhrase = true
  formatter.allowedUnits = [.minute]
  
  // Use the configured formatter to generate the string.
  let outputString = formatter.string(from: 300.0)
  Timber.d(outputString as Any)
  UIViewController.topMost?.view.makeToast(outputString)
}

/// 计时器
private func timing() {
  let formatter = DateComponentsFormatter()
  formatter.zeroFormattingBehavior = .pad
  formatter.unitsStyle = .positional // default
  formatter.allowedUnits = [.minute, .second]
  
  // Use the configured formatter to generate the string.
  let outputString = formatter.string(from: 3.446)
  Timber.d(outputString as Any)
  UIViewController.topMost?.view.makeToast(outputString)
}

/// 创建两个恰好相隔 1 天的日期。
private func oneDayApart() {
  let formatter = DateIntervalFormatter()
  formatter.dateStyle = .short
  formatter.timeStyle = .none
  
  // Create two dates that are exactly 1 day apart.
  let startDate = Date()
  let endDate = Date(timeInterval: 86400, since: startDate)
  
  // Use the configured formatter to generate the string.
  let outputString = formatter.string(from: startDate, to: endDate)
  Timber.d(outputString as Any)
  UIViewController.topMost?.view.makeToast(outputString)
}
